package game.test.ia;

import entity.GameEntity;
import entity.Position;
import entity.map.FieldEntity;
import entity.object.ICombatEntity;
import game.game.IControllerGame;
import game.game.ia.IGameIAModel;
import game.game.ia.transition.FigthingManager;

import java.util.List;

public class IAController implements IControllerGame, IControllerEngine
{
	protected IGameIAModel _model;

	public IAController(IGameIAModel pModel)
	{
		_model = pModel;
	}

	public void changePosition( Integer pNewX , Integer pNewY )
	{
		changePosition( _model.getPerso().getId() , pNewX , pNewY );
	}

	@Override
	public void changePosition( Integer pObjId , Integer pNewX , Integer pNewY )
	{
		changePosition( pObjId , new Position( pNewX, pNewY ) );

	}

	@Override
	public void changePosition( Integer pObjId , Position pNewPosition )
	{
		if ( isValidPosition( pNewPosition ) )
		{
			GameEntity objEntity = _model.getGameObject( pObjId );
			if ( objEntity != null )
			{
				objEntity.setPosition( pNewPosition );
			}
		}
	}

	private boolean isValidPosition( Position pNewPosition )
	{
		FieldEntity field = _model.getMap().getFieldEntity( pNewPosition );
		if ( field == null || field.isBlock() )
		{
			return false;
		}
		List<GameEntity> listObj = _model.getGameObjects();
		for ( GameEntity entity : listObj )
		{
			if ( pNewPosition.equals( entity.getPosition() ) )
			{
				return false;
			}
		}
		return true;
	}

	@Override
	public void launchAttack( Integer pNewX , Integer pNewY )
	{
		GameEntity objEntity = getGameEntity( new Position( pNewX, pNewY ) );
		if ( objEntity != null && objEntity instanceof ICombatEntity )
		{
			new FigthingManager().attack( (ICombatEntity) _model.getPerso() , (ICombatEntity) objEntity );
		}
	}

	private GameEntity getGameEntity( Position pNewPosition )
	{
		List<GameEntity> objEntityList = _model.getGameObjects();
		for ( GameEntity objEntity : objEntityList )
		{
			if ( objEntity.getPosition().equals( pNewPosition ) )
			{
				return objEntity;
			}
		}
		return null;
	}
}
